<template>
	<view class="layout" v-if="isShow">
		<view class="layoutbg">
			<!-- <image src="../../static/bg_title.png" mode="aspectFill"></image> -->
			<image :src="itemDetail.bg" mode="aspectFill"></image>
		</view>
		<view class="goBack" @click="goBack" :style="{top:(getStatusBarHeight()-2)+'px'}">
			<uni-icons type="back" color="#fff" size="20"></uni-icons>
		</view>
		<scorerank-view :score="score" @addScoreClick="addScoreClick" @rankClick="rankClick"></scorerank-view>
		<view :class="contentClass">
			<view class="title">
				<view class="bg">
					<!-- <image src="../../static/bg_title.png" mode="aspectFill"></image> -->
					<image :src="itemDetail.bg" mode="aspectFill"></image>
				</view>
				<view class="info" :style="{top:20+'px'}">
					<view class="title1">
						{{title}}
					</view>
					<view class="title2">
						{{itemNums+itemDetail.title}}
					</view>
					<view class="title3">
						{{itemDetail.subtitle}}
					</view>
				</view>
			</view>

			<view class="usernums" :style="{ height : numHeight + 'rpx'}">
				<view class="items">
					<view class="item" v-for="item in userNums"
						:style="{ border: item.isWin && isShowWinNums ? '2px solid red' : 'none' }">
						<view class="winnum">
							{{item.num}}
						</view>
						<view class="znum">
							{{item.pinyin}}
						</view>
						<view class="money">
							${{item.money}}
						</view>
					</view>
				</view>
				<canvas v-if="!isShowWin" class="canvas2" id="canvas2" disable-scroll=true canvas-id="canvas2"
					@touchstart="touchstart2" @touchmove="touchmove2" @touchend="touchend2"></canvas>
			</view>
		</view>

		<view class="menuBar" v-if="!isGaming">
			<view class="group" :style="{opacity:menuState?1:0,transform:menuState?'scaleX(1)':'scaleX(0)'}">
				<view class="item" hover-class="hoverItem" @click="autoPlayClick">
					<uni-icons type="checkbox" size="26"></uni-icons>
					<view class="text">自动刮奖</view>
				</view>

				<view class="item" hover-class="hoverItem" @click="autoPlayClickTen">
					<uni-icons type="loop" size="26"></uni-icons>
					<view class="text">连刮10张</view>
				</view>

				<view class="item" hover-class="hoverItem" @click="getNewOne">
					<uni-icons type="refresh" size="26"></uni-icons>
					<view class="text">换一张</view>
				</view>

				<view class="item" hover-class="hoverItem" @click="soundBtnClick">
					<uni-icons v-if="isOpenSound" type="mic" size="26"></uni-icons>
					<uni-icons v-if="!isOpenSound" type="micoff" size="26"></uni-icons>
					<view class="text">音效</view>
				</view>
			</view>
			<view class="close" @click="closeMenu">
				<uni-icons type="closeempty" size="20" color="#fff" v-if="menuState"></uni-icons>
				<uni-icons type="list" size="20" color="#fff" v-else></uni-icons>
			</view>
		</view>

	</view>


	<uni-popup ref="resultPopup" :is-mask-click="false" mask-background-color="rgba(0,0,0,0.8)">
		<view class="resultPopup">
			<view class="bg win" v-if="winMoney !== 0">
					<view class="text">{{'恭喜您中得'}}</view>
					<view class="text2">{{'$'+ winMoney}}</view>
			</view>
			<view class="bg loser" v-else>
				<view class="text">{{'机会只留给有准备的人，\n再试一次吧！'}}</view>
			</view>
			<view class="doubelBtn" @click="doubelBtnSubmit" v-if="winMoney !== 0 && !isDouble">
				<button type="primary">奖励翻倍</button>
			</view>
			<view class="submitBtn" @click="onSubmit" v-if="winMoney !== 0  && !isDouble">
				<button type="primary">再来一次</button>
			</view>
			<view class="submitBtnLose" @click="onSubmit" v-if="winMoney == 0">
				<button type="primary">再来一次</button>
			</view>

			<view class="close" @click="closeResult">
				<uni-icons type="close" color="#eee" size="40"></uni-icons>
			</view>
		</view>
	</uni-popup>

</template>

<script setup>
	import {
		ref
	} from "vue";
	import {
		getStatusBarHeight,
		getNavBarHeight,
		rpxToPx,
		pxToRpx
	} from "@/utils/system.js"
	import {
		getTotalUserScore,
		getUserScoreFromCloud,
		saveUserTotalScoreToCloud,
		getUserScore,
		addUserScore,
		saveUserAddScoreToLocal,
		SignInGetScore,
		SignInGetScoreLocal
	} from '../../store/scoreManager.js'

	import {
		onLoad,
		onShow,
		onReady,
		onBackPress
	} from "@dcloudio/uni-app"

	import {
		onMounted,
		getCurrentInstance
	} from 'vue'
	import {
		onShareAppMessage,
		onShareTimeline
	} from "@dcloudio/uni-app";
	import {
		getOffMony,
		getOnMony,
		padZero,
		getPinyinWithNum,
		getRandomNum,
		getRandomNumExcepts
	} from '../../utils/random.js'
	import {
		getTodayDateString,
		getTodayMonthString
	} from '../../utils/common.js'

const contentClass = ref(['content'])
	// 若在开发者工具中无法预览广告，请切换开发者工具中的基础库版本
	// 在页面中定义插屏广告
	let interstitialAd = null

	const title = ref('');
	const titleHeight = ref(0)
	const numHeight = ref(0)
	const isShowWin = ref(false);
	const content = ref("刮开覆盖膜，如果出现数字\"7\"则获得该数字下的所示积分，如果出现数字\"77\"则获得该数字下的所示积分的两倍，如果出现数字\"777\"则获得该数字下的所示积分的三倍。");
	const tips = ref(
		' 设置奖项：￥10,000,000、￥5,000,000、￥2,000,000、￥1,000,000、￥500,000、￥100,000、￥50,000、￥10,000、￥1,000、￥500、￥200、￥100')
	const userNums = ref([])

	const viewWidth = ref(0);
	const viewHeight = ref(0);
	const score = ref(0);
	const ctx = ref(null);

	const usertype = ref(0)

	const viewWidth2 = ref(0);
	const viewHeight2 = ref(0);
	const ctx2 = ref(null);

	const points = ref([]);
	const points2 = ref([]);

	const winPoints = ref(0);
	const userPoints = ref(0);
	const itemtype = ref(0)
	const resultPopup = ref(null);
	let winMoney = ref(0);

	const itemNums = ref(0)
	// canvas示例对象
	const instance = getCurrentInstance()
	const cost = ref(-50)
	const isShow = ref(false)

	const itemWidth = ref(55);
	const startX = ref(0);
	const startY = ref(0);
	// 是否显示刷新按钮
	const isSignup = ref(false)
	// 刮奖音效
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = false;
	innerAudioContext.src = "/static/audio/gua.m4a";
	// 是否显示中奖数字
	const isShowWinNums = ref(false);
	// 菜单栏
	const menuState = ref(true);
	// 声音
	const isOpenSound = ref(true)
	// 是否结束
	const isGameFinish = ref(false)
	const isGaming = ref(false)

	// 10次赢钱数
	const totalWinMoneys = ref(0)
	// 10次赢钱数
	const totalGameTimes = ref(0)
	// 是否没钱了
	const isNoMonyes = ref(false)
	const timer = ref(null)
	// 菜单栏是否可用
	const isMenuToolEnable = ref(false)
	// 1 签到增加金币 2双倍 3.工具栏
	const adType = ref(0)
	// 游戏是否准备完成  是否已经扣钱
	const isGameReady = ref(false)
	// 是否开启手动刮奖
	let isTouchGameStart = false;
	//菜单状态切换
	const closeMenu = () => {
		menuState.value = !menuState.value
	}
	
	// 换一张
	function getNewOne(){
		contentClass.value = ['content']
		setTimeout(()=>{
			contentClass.value = ['content','ld', 'ld-slide-ltr-out']
			setTimeout(()=>{
				contentClass.value = ['content','ld', 'ld-slide-rtl-in']
				isGameReady.value = false;
				if (isGameReady.value == false) {
					userNums.value = [];
					openNums.value = [];
					return onSubmit();
				}
			},500)
		},100)
		
		return true;
	}
	
	// 开始自动刮奖
	function autoPlayClick() {
		adType.value = 3
		if (isMenuToolEnable.value == false) {
			if (videoAd) {
				videoAd.show().catch(() => {
					// 失败重试
					videoAd.load()
						.then(() => videoAd.show())
						.catch(err => {
							console.error('激励视频 广告显示失败', err)
							uni.showToast({
								title: '广告拉取失败，请检查网络状况后重试',
								icon: "none",
								duration: 1500
							})
						})
				})
			}
		} else {
			// 停止老的计时器
			if (timer.value) {
				clearInterval(timer.value);
			}
			if (isGameFinish.value == true) {
				if (isGameReady.value == false) {
					refreshBtnSubmit();
					setTimeout(() => {
						singleAutoPlay()
					}, 600)
				} else {
					singleAutoPlay()
				}
			} else {
				singleAutoPlay()
			}
		}
	}

	function singleAutoPlay() {
		// 用户点击的时候再扣钱
		if(isGaming.value == false){
			score.value = saveUserAddScoreToLocal(cost.value)
			if(score.value>0){
				isGaming.value = true
			}else{
				return;
			}
		}
		isGaming.value = true
		let startX = 0;
		let startY = 0;
		timer.value = setInterval(() => {
			ctx2.value.clearRect(startX, startY, 150, 150);
			ctx2.value.draw(true);
			startX = startX + 50

			if (startX >= pxToRpx(uni.getWindowInfo().screenWidth - 200)) {
				startY += 120
				startX = 0;
			}
			if (pxToRpx(startY) >= numHeight.value) {
				clearInterval(timer.value)
				autoCheckShowAnwser()
				startX = 0;
				startY = 0;
				isGaming.value = false
			}
		}, 50);
	}

	// 单次刮奖不兑奖
	function singleAutoPlayNotCheck() {
		// 用户点击的时候再扣钱
		let startX = 0;
		let startY = 0;
		timer.value = setInterval(() => {
			isShowWinNums.value = true
			ctx2.value.clearRect(startX, startY, 150, 150);
			ctx2.value.draw(true);
			startX = startX + 50

			if (startX >= pxToRpx(uni.getWindowInfo().screenWidth - 200)) {
				startY += 120
				startX = 0;
			}
			if (pxToRpx(startY) >= numHeight.value) {
				clearInterval(timer.value)
				isGameReady.value = false;
				isGameFinish.value = true;
				totalWinMoneys.value += winMoney.value;
				winMoney.value = 0;
				isShowWinNums.value = true
				startX = 0;
				startY = 0;
				tenTimesAutoPlayGame()
			}
		}, 50);
	}

	// 连抽10次
	function autoPlayClickTen() {
		adType.value = 3
		if (isMenuToolEnable.value == false) {
			if (videoAd) {
				videoAd.show().catch(() => {
					// 失败重试
					videoAd.load()
						.then(() => videoAd.show())
						.catch(err => {
							console.error('激励视频 广告显示失败', err)
							uni.showToast({
								title: '广告拉取失败，请检查网络状况后重试',
								icon: "none",
								duration: 1500
							})
						})
				})
			}
		} else {
			isGaming.value = true
			totalWinMoneys.value = 0;
			totalGameTimes.value = 0;
			if (timer.value) {
				clearInterval(timer.value);
			}
			tenTimesAutoPlayGame()
		}
	}
	// 开始10次递归玩游戏
	function tenTimesAutoPlayGame() {
		if (totalGameTimes.value != 10) {
			totalGameTimes.value += 1
			if (isGameFinish.value == true) {
				refreshBtnSubmit();
				score.value = saveUserAddScoreToLocal(cost.value)
				// 判断是否没钱了
				if (score.value > 0) {
					setTimeout(() => {
						singleAutoPlayNotCheck()
					}, 600)
				} else { //没钱提前结束游戏
					totalGameTimes.value = 10
					isGaming.value = false
					winMoney.value = totalWinMoneys.value;
					autoCheckShowAnwser()
					if (timer.value) {
						clearInterval(timer.value);
					}
				}
			} else {
				singleAutoPlayNotCheck()
			}
		} else {
			winMoney.value = totalWinMoneys.value;
			autoCheckShowAnwser()
			isGaming.value = false
		}
	}

	// 关闭声音按钮点击
	function soundBtnClick() {
		isOpenSound.value = !isOpenSound.value
		uni.setStorageSync("isOpenSound", isOpenSound.value)
	}

	async function autoCheckShowAnwser() {
		if (isOpenSound.value === true) {
			if (winMoney.value != 0) {
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = false;
				innerAudioContext.src =
					"/static/audio/huanhu.mp3";
				innerAudioContext.play();
			} else {
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = false;
				innerAudioContext.src =
					"/static/audio/kexi.mp3";
				innerAudioContext.play();
			}
		}
		isGameReady.value = false;
		isShowWin.value = true;
		isShowWinNums.value = true;
		isGameFinish.value = true;
		isGameReady.value = false;
		setTimeout(() => {
			resultPopup.value.open();
			score.value = saveUserAddScoreToLocal(winMoney.value, itemtype.value,itemDetail.value._id,itemDetail.value.name)
		}, 1000)
	}

	onShow(() => {
		score.value = getTotalUserScore();
		loadHomeAd()
		// 获取音效开关
		isOpenSound.value = uni.getStorageSync("isOpenSound")
		const menuValueString = uni.getStorageSync("isEnableMenuTool" + title.value);
		const dayString = getTodayDateString();
		if (menuValueString && menuValueString === dayString) {
			isMenuToolEnable.value = true;
		} else {
			isMenuToolEnable.value = false;
		}
	})
	
	// 点击排名按钮
	function rankClick(){
		// console.log('rankClick');
		uni.navigateTo({
			url: '/pages/index/rank?'+ 'usertype=2'  +'&gameid='+itemDetail.value._id+'&gamename='+itemDetail.value.name+'&gamebg='+itemDetail.value.bg
		})
	}
	

	function goBack() {
		// drawInit();
		// 停止刮奖
		if (timer.value) {
			clearInterval(timer.value);
		}

		uni.navigateBack({
			success: () => {
				saveUserTotalScoreToCloud()
			},
			fail: () => {
				 saveUserTotalScoreToCloud()
				uni.reLaunch({
					url: '/pages/index/shouye'
				})
			}
		})
	}
	// 和生命周期函数同级
	// 和生命周期函数同级
	// 返回值为true 不允许返回 否则允许
	onBackPress((options) => {
		// 点击虚拟键或者侧滑的时候触发（不允许返回）
		if (options.from === 'backbutton') {
			return true
		}
		// 否则则允许返回
		return false;
	})

	const itemDetail = ref({})

	const isNewUser = ref(false);
	onLoad(e => {
		isNewUser.value = e.isNewUser;
		itemDetail.value = JSON.parse(e.itemDetail);
		title.value = itemDetail.value.name;
		if (!itemDetail.value.title || !itemDetail.value.cost) {
			uni.reLaunch({
				url: '/pages/detail/detail0' + '?title=平安喜乐'
			})
			return
		}
		isShow.value = true
		cost.value = itemDetail.value.cost;
		titleHeight.value = getStatusBarHeight() + 10;
		numHeight.value = pxToRpx(uni.getWindowInfo().screenHeight - getNavBarHeight()) - (350 + 20)
		itemNums.value = Math.floor(numHeight.value / 120.0) * 5;
		setTimeout(() => {
			creatNums();
		}, 1000)

		// 在页面onLoad回调事件中创建激励视频广告实例
		if (wx.createRewardedVideoAd) {
			videoAd = wx.createRewardedVideoAd({
				adUnitId: 'adunit-68d6f70cfd097fdb'
			})
			videoAd.onLoad(() => {})
			videoAd.onError((err) => {
				console.error('激励视频光告加载失败', err)
			})
			videoAd.onClose((res) => {
				// 用户点击了【关闭广告】按钮
				if (res && res.isEnded) {
					// 正常播放结束，可以下发游戏奖励
					if (adType.value == 1) {
						score.value = saveUserAddScoreToLocal(1000, 1)
					} else if (adType.value == 2) {
						console.log("Add双倍积分:", winMoney.value);
						score.value = saveUserAddScoreToLocal(winMoney.value, 99,itemDetail.value._id,itemDetail.value.name)
						isDouble.value = true
					} else if (adType.value == 3) {
						const dayString = getTodayDateString();
						uni.setStorageSync("isEnableMenuTool" + title.value, dayString);
						isMenuToolEnable.value = true;
					}

				} else {
					if (adType.value == 1) {
						uni.showToast({
							title: '未获得奖励，每次完成广告观看可获得1000金币奖励',
							icon: "none",
							duration: 3000
						})
					} else if (adType.value == 2) {
						// 播放中途退出，不下发游戏奖励
						uni.showToast({
							title: '未获得奖励，观看完成可获得当前得奖的双倍奖励！',
							icon: "none",
							duration: 3000
						})
					} else if (adType.value == 3) {
						// 播放中途退出，不下发游戏奖励
						uni.showToast({
							title: '未获得奖励，仅观看一次广告，全天可用！',
							icon: "none",
							duration: 3000
						})
					} else {
						uni.showToast({
							title: '中途退出，未获得奖励！',
							icon: "none",
							duration: 2000
						})
					}
				}
			})
		}
	})
	let isDouble = ref(false)
	let videoAd = null

	function doubelBtnSubmit() {
		adType.value = 2;
		isSignup.value = false
		if (videoAd) {
			videoAd.show().catch(() => {
				// 失败重试
				videoAd.load()
					.then(() => videoAd.show())
					.catch(err => {
						console.error('激励视频 广告显示失败', err)
						uni.showToast({
							title: '广告拉取失败，请检查网络状况后重试',
							icon: "none",
							duration: 1500
						})
					})
			})
		}

		// 在页面onLoad回调事件中创建插屏广告实例
		if (wx.createInterstitialAd) {
			interstitialAd = wx.createInterstitialAd({
				adUnitId: 'adunit-1722f7e6276cc54a'
			})
			interstitialAd.onLoad(() => {})
			interstitialAd.onError((err) => {
				console.error('插屏广告加载失败', err)
			})
			interstitialAd.onClose(() => {})
		}
	}

	//分享给好友
	// onShareAppMessage((e) => {
	// 	return {
	// 		title: "喜乐刮刮卡",
	// 		path: "/pages/index/shouye"
	// 	}
	// })

	// //分享朋友圈
	// onShareTimeline(() => {
	// 	return {
	// 		title: "喜乐刮刮卡",
	// 		path: "/pages/index/shouye"
	// 	}
	// })



	function loadHomeAd() {
		if (itemDetail.value.isShowAds == false) {
			return;
		}
		const key = "detail-AD" + itemDetail.value.type;
		const count = uni.getStorageSync(key);
		const day = getTodayDateString();
		if (count) {
			const c = count.split("--");
			if (c[0] == day) {
				if (Number(c[1]) < itemDetail.value.adTimes) {
					loadAD()
					uni.setStorageSync(key, day + "--" + (Number(c[1]) + 1))
				}
			} else {
				loadAD()
				uni.setStorageSync(key, day + "--" + 1)
			}
		} else {
			loadAD()
			uni.setStorageSync(key, day + "--" + 1)
		}
	}

	function loadAD() {
		console.error('加载插屏广告')
		// 在适合的场景显示插屏广告
		if (interstitialAd) {
			interstitialAd.show().catch((err) => {
				console.error('插屏广告显示失败', err)
			})
		}
	}

	function addScoreClick() {
		adType.value = 1
		if (videoAd) {
			videoAd.show().catch(() => {
				// 失败重试
				videoAd.load()
					.then(() => videoAd.show())
					.catch(err => {
						console.error('激励视频 广告显示失败', err)
						uni.showToast({
							title: '广告拉取失败，请检查网络状况后重试',
							icon: "none",
							duration: 1500
						})
					})
			})
		}
	}

	// 获取页面实例对象
	onMounted(() => {
		drawInit2();

	})

	// 获取元素宽高
	function getViewHW2() {
		let info = uni.createSelectorQuery().in(instance).select(".usernums");
		return new Promise((resolve, reject) => {
			info.boundingClientRect((data) => {
				viewWidth2.value = data.width + 40
				viewHeight2.value = data.height + 40
				resolve()
			}).exec(function(res) {
				// 注意：exec方法必须执行，即便什么也不做，否则不会获取到任何数据
			})
		})
	}

	async function drawInit2() {
		await getViewHW2()
		ctx2.value = uni.createCanvasContext('canvas2', instance)
		ctx2.value.clearRect(0, 0, viewWidth2.value, viewHeight2.value)
		ctx2.value.setFillStyle('#bbb'); // 填充颜色
		ctx2.value.fillRect(0, 0, viewWidth2.value, viewHeight2.value); // 填充区域（x,y,宽,高）
		let x = 0;
		let y = 0;
		for (var i = 0; i < viewHeight2.value / itemWidth.value + 1; i++) {
			y = i * (itemWidth.value + 15);
			for (var j = 0; j < viewWidth2.value / itemWidth.value + 1; j++) {
				x = j * (itemWidth.value + 15)
				ctx2.value.drawImage('../../static/ic_wallet.png', x, y, itemWidth.value, itemWidth.value);
			}
		}

		ctx2.value.draw(); // 将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中。
	}

	function closeResult() {
		resultPopup.value.close();
	}

	function refreshBtnSubmit() {
		if (isGameReady.value == false) {
			return onSubmit();
		}
		return true;
	}

	function onSubmit() {
		isDouble.value = false
		if (score.value >= cost.value * -1) {
			isGameReady.value = true;
			resultPopup.value.close();
			winMoney.value = 0;
			isNoMonyes.value = false;
			isShowWinNums.value = false;

			isShowWin.value = false;
			isDouble.value = false;
			ctx.value = null;
			points.value = [];
			ctx2.value = null;
			points2.value = [];
			winPoints.value = 0;
			userPoints.value = 0;
			drawInit2();
			setTimeout(() => {
				if (score.value >= 0) {
					creatNums();
				}
			}, 300);
			return true;
		} else {
			isGameReady.value = false;
			isNoMonyes.value = true;
			resultPopup.value.close();
			uni.showToast({
				title: '您的金币不够了，点击上方金币"+"按钮观看广告增加1000金币。',
				icon: "none",
				duration: 2000
			})
			return false;
		}
	}


	function isObject(value) {
		return value instanceof Object && value !== null;
	}
	// https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/guaguale/icon/1.png
	function creatNums() {
		let open = itemDetail.value.winNumObjs;
		let user = [];
		// 可以中两个数的概率
		let isDoble = getRandomNum(itemDetail.value.doubleRate) > 1000;
		let isContainWin = true;
		// 想要提取所有对象的'name'属性
		let openNums = open.map(obj => obj.winNum);
		// while循环添加数字 {"winNum":7,"multiple":1}
		while (user.length != itemNums.value) {
			// 按照中奖率的数字获取随机数
			const num = getRandomNum(itemDetail.value.numRate);
			const winNum = open.find(item => item.winNum === num);
			if (winNum) {
				if (isContainWin) {
					user.push(num)
					isContainWin = false;
				} else if (isDoble) {
					user.push(num)
					isDoble = false;
				}
			} else {
				// 填充不中奖的数字
				if (num < 100) {
					user.push(num)
				}else{
					user.push(getRandomNumExcepts(99, openNums))
				}
			}
		}
		
		const isNewUserWin = false;
		// 新用户不中的话 50%再中一次
		try {
			if (isNewUser.value == 'true' && isContainWin == true) {
				if (getRandomNum(100) > 40) {
					console.log("新用户50%命中");
					user[getRandomNum(user.length - 1)] = open[0].winNum;
					isNewUserWin = true;
				}
			}
		} catch (e) {
		
		}

		userNums.value = [];
		// 获取索引
		for (let index in user) {
			// 中奖
			let money = "";
			let isWin = false;
			const temp = user[index];
			const winNum = open.find(item => item.winNum === temp);
			if (winNum) {
				if(isNewUserWin){
					money = getOnMony(itemDetail.value.winRate, itemDetail.value.winsMultipleMoney);
					winMoney.value += money * winNum.multiple;
				}else{
					if (winNum.multiple > 2) {
						money = getOnMony(itemDetail.value.winRate, itemDetail.value.winsMultipleMoney);
						winMoney.value += money * winNum.multiple;
					} else {
						money = getOnMony(itemDetail.value.winRate, itemDetail.value.winsMoney);
						winMoney.value += money * winNum.multiple;
					}
				}
				isWin = true;
			} else {
				money = getOffMony(itemDetail.value.winsMoney)
			}
			const item = {
				num: padZero(temp, 2),
				pinyin: getPinyinWithNum(temp),
				money,
				isWin
			}
			userNums.value.push(item);
		}
	}


	/*
		canvas2
	**/
	function touchstart2(e) {
		// 用户点击的时候再扣钱
		if(isTouchGameStart == false){
			score.value = saveUserAddScoreToLocal(cost.value)
			if(score.value>0){
				isTouchGameStart = true
			}
		}
		startX.value = e.changedTouches[0].x;
		startY.value = e.changedTouches[0].y;
	}

	function touchmove2(e) {
		// 不满足游戏条件直接返回
		if(isTouchGameStart == false) return;
		let moveX = e.changedTouches[0].x
		let moveY = e.changedTouches[0].y
		userPoints.value = userPoints.value + 1

		let currentStartX = e.changedTouches[0].x
		let currentStartY = e.changedTouches[0].y


		ctx2.value.clearRect(startX.value, startY.value, 100, 100);

		ctx2.value.draw(true);
		startX.value = e.changedTouches[0].x
		startY.value = e.changedTouches[0].y

	}

	function touchend2(e) {
		// 不满足游戏条件直接返回
		if(isTouchGameStart == false) return;
		chechShowAnwser()
	}

	function chechShowAnwser() {
		if (userPoints.value >= 200) {
			isShowWin.value = true;
			setTimeout(() => {
				if (isOpenSound.value === true) {
					if (winMoney.value != 0) {
						const innerAudioContext = uni.createInnerAudioContext();
						innerAudioContext.autoplay = false;
						innerAudioContext.src =
							"/static/audio/huanhu.mp3";
						innerAudioContext.play();
					} else {
						const innerAudioContext = uni.createInnerAudioContext();
						innerAudioContext.autoplay = false;
						innerAudioContext.src =
							"/static/audio/kexi.mp3";
						innerAudioContext.play();
					}
				}
				
				isGameFinish.value = true;
				isShowWin.value = true;
				isShowWinNums.value = true
				isTouchGameStart = false;
				setTimeout(() => {
					resultPopup.value.open();
					score.value = saveUserAddScoreToLocal(winMoney.value, itemtype.value,itemDetail.value._id,itemDetail.value.name)
				}, 1000)

			}, 500)
		} else {
			isShowWinNums.value = false
			isShowWin.value = false;
			isShowWinNums.value = false
		}

	}
</script>

// <!-- // scss 语言类型  scoped css样式的类名仅限当前页面 不污染其它页面 -->
<style lang="scss">
	@import url('../../components/transition-min/transition.min.css');
	@font-face {
		font-family: NumFont;
		src: url('https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/font/HONORSans-Bold.ttf');
	}

	.layout {
		width: 100%;
		height: 100vh;
		background-color: #008B8B;
		position: relative;
		.layoutbg {
			position: absolute;
			top: 0rpx;
			left: 0rpx;
			width: 100%;
			height: 100vh;
			image {
				width: 100%;
				height: 100%;
				opacity: 1;
			}
		}

		.goBack {
			position: fixed;
			margin-left: 10rpx;
			width: 38px;
			height: 38px;
			background: rgba(0, 0, 0, 0.5);
			border-radius: 50%;
			backdrop-filter: blur(10rpx);
			border: 1rpx solid rgba(255, 255, 255, 0.3);
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 1000;
		}




		.content {
			// width: 100%;
			height: calc(100vh);
			background-color: #de3018;
			margin-top: 0rpx;
			box-sizing: content-box;
			border-radius: 20px;
			overflow: hidden;
			position: relative;
			display: flex;
			align-items: center;
			flex-direction: column;

			.title {
				position: relative;
				width: 100%;

				.bg {
					position: absolute;
					top: 0rpx;
					left: 0rpx;
					width: 100%;
					height: 100vh;

					image {
						width: 100%;
						height: 100%;
						opacity: 0.8;
					}
				}

				.info {
					position: absolute;
					top: 0rpx;
					left: 0rpx;
					width: 100%;
					height: 350rpx;
					display: flex;
					align-items: center;
					flex-direction: column;

					.title1 {
						width: 100%;
						font-size: 110rpx;
						font-weight: bold;
						text-align: center;
						color: #008B8B;
						// color: white;
					}

					.title2 {
						width: 80%;
						font-size: 18px;
						text-align: center;
						color: #de3018;
						background-color: #ffe21d;
						padding: 0 20rpx;
					}

					.title3 {
						width: 100%;
						margin-top: 20rpx;
						font-size: 14px;
						text-align: center;
						color: #fff;
						padding: 0 20rpx;
					}
				}
			}

			.usernums {
				margin-top: 380rpx;
				position: relative;
				width: 95%;
				background-color: #d8d7d7;
				border: 10rpx solid #008B8B;
				.items {
					width: 100%;
					display: grid;
					grid-template-columns: repeat(5, 1fr);
					row-gap: 10rpx;
					column-gap: 20rpx;
					padding: 5rpx;

					.item {
						width: 110rpx;
						height: 110rpx;
						// background-color: #d1d0d0;
						border-radius: 50%;

						.winnum {
							margin-top: 10rpx;
							font-size: 50rpx;
							text-align: center;
							color: #efefef;
							font-weight: bold;
							-webkit-text-stroke: 1px black;
							font-family: 'NumFont';
						}

						.znum {
							font-size: 16rpx;
							text-align: center;
							color: black;
							margin-top: -5rpx;
						}

						.money {
							font-size: 20rpx;
							text-align: center;
							color: black;
							font-weight: bold;
							margin-top: 0rpx;
						}
					}
				}

				.canvas2 {
					position: absolute;
					left: 0;
					top: 0;
					width: 100%;
					height: 100%;
				}
			}
		}

		.menuBar {
			z-index: 100;
			position: fixed;
			bottom: 20px;
			right: 50%;
			transform: translateX(50%);
			display: flex;
			align-items: center;
			flex-direction: row;

			.group {
				display: grid;
				grid: auto-flow / 1fr 1fr 1fr 1fr;
				gap: 30rpx;
				transition: 0.3s;
				transform-origin: right center;

				.item {
					background: #ffe21d;
					width: 100rpx;
					height: 100rpx;
					border-radius: 50%;
					border: 2px solid #de3018;
					display: flex;
					align-items: center;
					justify-content: center;
					flex-direction: column;
					box-shadow: 0 0 15rpx rgba(0, 0, 0, 0.6);

					.text {
						margin-top: -5rpx;
						font-size: 23rpx;
						transform: scale(0.85);
					}
				}

				.hoverItem {
					transform: scale(0.95);
				}
			}

			.close {
				width: 70rpx;
				height: 70rpx;
				background: rgba(0, 0, 0, 0.9);
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 0rpx;
				line-height: 1em;
				margin-left: 20px;
			}
		}

	}


	.resultPopup {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-bottom: 150rpx;

		.bg {
			background: no-repeat center;
			background-size: cover;
			position: relative;
		}

		.win {
			width: 735rpx;
			height: 986rpx;
			background-image: url('https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/image/bg_win_2.png');
			background-size: 500rpx 655rpx;

			.text {
				text-align: center;
				position: absolute;
				width: 50%;
				top: 585rpx;
				left: 25%;
				color: #fff;
				font-size: 45rpx;
				font-weight: bolder;
			}
			.text2 {
				text-align: center;
				position: absolute;
				width: 50%;
				top: 645rpx;
				left: 25%;
				color: #fff;
				font-size: 55rpx;
				font-weight: bolder;
			}
		}

		.loser {
			width: 735rpx;
			height: 986rpx;
			background-image: url('https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/image/bg_lose_2.png');
			background-size: 500rpx 605rpx;

			.text {
				line-height: 80rpx;
				text-align: center;
				position: absolute;
				padding: 0 160rpx;
				width: 100%;
				top: 545rpx;
				left: 0;
				color: #fff;
				font-size: 40rpx;
				font-weight: bolder;
			}
		}

		.submitBtn {
			width: 30%;
			margin-top: 40rpx;
			border-radius: 10rpx;

			button {
				background: transparent;
				font-size: 25rpx;
			}
		}

		.submitBtnLose {
			width: 60%;
			margin-top: -160rpx;

			button {
				background: #ee4626;
			}
		}

		.doubelBtn {
			width: 60%;
			margin-top: -160rpx;

			button {
				background: #F5D54D;
				color: #F5514d;
			}
		}

		.close {
			position: absolute;
			margin-left: 10rpx;
			width: 38px;
			height: 38px;
			// background: rgba(0, 0, 0, 0.5);
			border-radius: 50%;
			backdrop-filter: blur(10rpx);
			// border: 1rpx solid rgba(255, 255, 255, 0.3);
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 1000;
			right: 100rpx;
			top: 200rpx;
		}
	}

	.footer {
		position: fixed;
		width: 80rpx;
		height: 80rpx;
		bottom: 50rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		image {
			width: 80rpx;
			height: 80rpx;
		}
	}
</style>